package cn.turboinfo.fuyang.api.gateway.web.framework.http

import cn.turboinfo.fuyang.api.gateway.admin.framework.http.AdminServletWrapperException
import cn.turboinfo.fuyang.api.gateway.mini.framework.http.MiniServletWrapperException
import cn.turboinfo.fuyang.api.gateway.share.framework.http.ShareServletWrapperException
import org.apache.commons.lang3.StringUtils
import org.springframework.boot.web.servlet.error.ErrorController
import org.springframework.ui.ModelMap
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import javax.servlet.ServletException
import javax.servlet.http.HttpServletRequest

@RestController
class CommonErrorController : ErrorController {

    @RequestMapping("/error")
    @Throws(Exception::class)
    fun handleError(request: HttpServletRequest, modelMap: ModelMap) {
        // 捕获从filter等处过来的异常或者处理404等 然后将异常重新抛出给全局处理
        val exception = request.getAttribute("javax.servlet.error.exception") as Exception?
        if (exception != null) {
            if (exception is ServletException) {
                val forwardUri = request.getAttribute("javax.servlet.forward.request_uri") as String
                val mappingUri = StringUtils.substringAfter(forwardUri, request.contextPath)
                if (mappingUri.startsWith("/admin/")) {
                    throw AdminServletWrapperException(exception.cause)
                }
                if (mappingUri.startsWith("/mini/")) {
                    throw MiniServletWrapperException(exception.cause)
                }
                if (mappingUri.startsWith("/share/")) {
                    throw ShareServletWrapperException(exception.cause)
                }
            }
            throw exception
        }
    }
}
